<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    class="app-container noPd"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <lb-table
      :column="tableData.column"
      :data="tableData.data"
      pagination
      border
      background
      height="640"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
    >
    </lb-table>
    <operate
      :id="id"
      :type="type"
      :visible.sync="show"
      @close="close"
    ></operate>
  </lb-layout>
</template>

<script>
import { mapState } from "vuex";
import auth from "@/plugins/auth";
import { exportExecl } from "@/utils/export-execl";
import { priceVersionList } from "@/api/quota/energy";
import { list, budget } from "@/api/quota/budget";
import CascaderSelect from "@/components/Select/CascaderSelect";
import operate from "@/views/work/quota/budget/components/operate";

export default {
  dicts: ["energy_type", "target_type", "energy_budget_manage_audit_status"],
  name: "budget",
  components: {
    operate,
    CascaderSelect,
  },
  data() {
    return {
      // isNhgl: false, //能耗管理
      // isYnbm: false, //用能人员
      // isCaiZheng: false, //财政
      //弹窗
      id: "",
      type: 0,
      show: false,
      // 部门树选项
      versionOption: [],
      apsForm: {
        formRef: "form",
        labelWidth: "120px",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            deptId: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                return (
                  <div>
                    <CascaderSelect
                      values={that.$refs?.form?.getFieldsValue().deptId}
                      value={that.$refs?.form?.getFieldsValue().deptId}
                      varient={"energy"}
                      size={"small"}
                      placeholder={"用能单位"}
                      onInput={that.handlerLiandong}
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            energyPriceVersion: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                // 数据严谨处理,处理后端数据异常情况
                let valNum =
                  that.$refs?.form?.getFieldsValue().energyPriceVersion;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "参考额度标准版本号",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "energyPriceVersion",
                            value
                          );
                        },
                      },
                    },
                    [
                      that.versionOption.map((item) => {
                        return h("el-option", {
                          props: {
                            label: item,
                            value: item,
                            key: item,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            energyType: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.energy_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().energyType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "能耗种类",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("energyType", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            targetType: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.target_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().targetType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "指标类型",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("targetType", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            auditEvent: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.energy_budget_manage_audit_status.some(
                  (item) => {
                    arr.push(item);
                  }
                );
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().auditEvent;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "预算状态",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("auditEvent", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            budgetYear: {
              typeName: "el-date-picker",
              type: "year",
              "value-format": "yyyy",
              placeholder: "预算年份",
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            {
              label: "电费预算",
              type: "success",
              typeName: "el-button",
              plain: true,
              size: "small",
              display: true,
              click: () => this.handleBudget(),
            },
            {
              label: "导出",
              type: "warning",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-upload2",
              plain: true,
              display: true,
              click: () => this.handleExport(),
            },
          ],
        },
      },
      tableData: {
        column: [
          {
            label: "所属用能单位",
            prop: "sysDeptName",
            width: 150,
            showOverflowTooltip: true,
          },
          {
            label: "预算年度",
            prop: "budgetYear",
            width: 100,
            showOverflowTooltip: true,
          },
          {
            prop: "unitArea",
            label: "用能面积（m²）",
            width: 160,
            showOverflowTooltip: true,
          },
          {
            prop: "quotaAllocationVal",
            label: "能耗实际分配额度N（kwh/m2）",
            width: 260,
            showOverflowTooltip: true,
          },
          {
            prop: "energyPriceAvg",
            label: "电单价M（元/KWH）",
            width: 200,
            showOverflowTooltip: true,
          },
          {
            prop: "subsidyVal",
            label: "电费补贴（0元）",
            width: 150,
          },
          {
            prop: "carbonNeutral",
            label: "碳中和预算（P元）",
            width: 160,
          },
          // {
          //   prop: "energyType",
          //   label: "能耗种类",
          //   width: 150,
          //   align: "center",
          //   render: (h, scope) => {
          //     return (
          //       <div>
          //         <dict-tag
          //           options={this.dict.type.energy_type}
          //           value={scope.row.energyType}
          //         />
          //       </div>
          //     );
          //   },
          // },
          // {
          //   prop: "targetType",
          //   label: "指标类型",
          //   width: 150,
          //   align: "center",
          //   render: (h, scope) => {
          //     return (
          //       <div>
          //         <dict-tag
          //           options={this.dict.type.target_type}
          //           value={scope.row.targetType}
          //         />
          //       </div>
          //     );
          //   },
          // },
          {
            prop: "auditStatus",
            label: "申报状态",
            width: 150,
            align: "center",
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.energy_budget_manage_audit_status}
                    value={scope.row.auditStatus}
                  />
                </div>
              );
            },
          },
          {
            prop: "declareTime",
            label: "申报时间",
            width: 180,
            showOverflowTooltip: true,
          },
          {
            prop: "summaryAuditTime",
            label: "汇总审批时间",
            width: 180,
            showOverflowTooltip: true,
          },
          {
            prop: "declareContent",
            label: "申报理由",
            width: 150,
            showOverflowTooltip: true,
          },
          {
            prop: "auditOpinion",
            label: "审核意见",
            width: 150,
            showOverflowTooltip: true,
          },
          {
            label: "操作",
            width: 200,
            fixed: "right",
            render: (h, scope) => {
              let a, b, c, d;
              if (
                auth.hasPermi("energy:manage:audit:0") &&
                scope.row.auditStatus === 0
              ) {
                a = (
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-edit"
                    onClick={() => {
                      this.operate(scope.row.id, 1);
                    }}
                  >
                    申报
                  </el-button>
                );
              } else {
                a = <div style="display:none"></div>;
              }
              if (
                auth.hasPermi("energy:manage:audit:1") &&
                scope.row.auditStatus === 1
              ) {
                b = (
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-edit-outline"
                    onClick={() => {
                      this.operate(scope.row.id, 2);
                    }}
                  >
                    汇总审批
                  </el-button>
                );
              } else {
                b = <div style="display:none"></div>;
              }
              if (
                auth.hasPermi("energy:manage:audit:2") &&
                scope.row.auditStatus == 2
              ) {
                c = (
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-edit-outline"
                    onClick={() => {
                      this.operate(scope.row.id, 3);
                    }}
                  >
                    终极审批
                  </el-button>
                );
              } else {
                c = <div style="display:none"></div>;
              }
              d = (
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-view"
                  onClick={() => {
                    this.detail(scope.row.id);
                  }}
                >
                  详情
                </el-button>
              );
              return (
                <div>
                  {a}
                  {b}
                  {c}
                  {d}
                </div>
              );
            },
          },
        ],
        data: [],
      },
      radio: 0,
      currentPage: 1,
      pageSize: 20,
      total: 0,
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user,
    }),
  },
  mounted() {
    // 添加总会管理员角色判断zjuadmin
    this.judgePermi();
    this.getVersionList();
  },
  methods: {
    judgePermi() {
      if (auth.hasPermi("energy:manage:budget")) {
        this.apsForm.formConfig.formSoltButton[2].display = false;
      }
      if (auth.hasPermi("energy:manage:export")) {
        this.apsForm.formConfig.formSoltButton[3].display = false;
      }
      // if (auth.hasRole("ynbm_leader") || auth.hasRole("ynbm_user")) {
      //   this.isYnbm = true;
      //   // this.$refs?.form?.setFieldValue("deptId", this.userInfo.deptId);
      // }
      // if (auth.hasRole("nhgl_user") || auth.hasRole("nhgl_leader")) {
      //   this.isNhgl = true;
      // }
      // if (auth.hasRole("czbm_leader")) {
      //   this.isCaiZheng = true;
      // }
      this.handlerSearchDetail();
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        ...this.$refs?.form.getFieldsValue(),
      };
      exportExecl("额度预算", "/energy/budget-manage/export", data, this);
    },
    /** 电费预算操作 */
    handleBudget() {
      const data = this.$refs?.form.getFieldsValue();
      if (!data.deptId) {
        this.$message.warning("请选择用能单位");
        return false;
      }
      if (!data.energyType) {
        this.$message.warning("请选择能耗种类");
        return false;
      }
      if (!data.targetType) {
        this.$message.warning("请选择指标类型");
        return false;
      }
      if (!data.energyPriceVersion) {
        this.$message.warning("请选择参考额度标准版本号");
        return false;
      }
      if (!data.budgetYear) {
        this.$message.warning("请选择能耗预算年份");
        return false;
      }
      budget(data)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.handlerSearchDetail();
          this.$message.success("操作成功");
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300082");
        });
    },
    handlerLiandong(val) {
      let result;
      if (val && val.length > 0) {
        result = val[val.length - 1];
      } else {
        result = null;
      }
      this.$refs?.form?.setFieldValue("deptId", result);
    },
    //获取版本号
    getVersionList() {
      priceVersionList()
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.versionOption = res.data;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300065");
        });
    },
    operate(id, type) {
      this.id = id;
      this.type = type;
      this.show = true;
    },
    detail(id) {
      this.id = id;
      this.type = 0;
      this.show = true;
    },
    close(status) {
      this.show = false;
      if (status) this.handlerSearchDetail();
    },
    async initData(currentPage, pageSize, data) {
      let that = this;
      let query = {
        ...data,
      };
      if (currentPage) {
        query.pageNum = currentPage;
      } else {
        query.pageNum = that.currentPage;
      }
      if (pageSize) {
        query.pageSize = pageSize;
      } else {
        query.pageSize = that.pageSize;
      }
      that.$store.commit("app/updateApiCount", "add");
      await list(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res.rows;
          that.total = res.total;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300081");
        });
    },
    handlerSearchDetail(val) {
      //val===1 删除操作成功后分页边界值处理
      let currentPage = 1;
      if (val === 1) {
        if (
          this.total === (this.currentPage - 1) * this.pageSize + 1 &&
          this.total !== 0 &&
          this.currentPage > 1
        ) {
          currentPage = this.currentPage - 1;
          this.currentPage = currentPage;
        } else {
          currentPage = this.currentPage;
        }
      } else {
        currentPage = this.currentPage;
      }
      const data = {
        ...this.$refs?.form?.getFieldsValue(),
      };
      this.initData(currentPage, this.pageSize, data);
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    handleReset() {
      //重置
      this.$refs?.form?.resetFields();
      // if (this.isYnbm) {
      //   this.$refs?.form?.setFieldValue("deptId", this.userInfo.deptId);
      // }
      this.handlerSearchDetail();
    },
  },
};
</script>
